package com.summer.applet.entity;

import java.awt.Graphics;

/**
 * 导演*/
public class GameDirector {
	
	public static final GameDirector gameDirector = new GameDirector();
	
	private final DrawTask mDrawTask = new DrawTask();
	private PlayScene playScene;
	private CollisionDetection gameRule;
	
	private GameDirector(){
		
	}
	
	public void addCollisionDetection(CollisionDetection gameRule){
		this.gameRule = gameRule;
	}
	
	public void addPlayScene(PlayScene playScene){
		this.playScene = playScene;
	}
	
	public void start(){
		mDrawTask.start();
	}
	
	public synchronized void goPlay(){
		mDrawTask.goPlay();
	}
	
	public synchronized void pause(){
		mDrawTask.isPause = true;
	}
	
	public synchronized void stop(){
		mDrawTask.isRun = false;
	}
	
	private class DrawTask extends Thread {

		private volatile boolean isRun;
		private volatile boolean isPause;
		private final Object lock = new Object[0];

		private DrawTask() {
			isRun = true;
			isPause = false;
		}

		public void goPlay() {
			isRun = true;
			isPause = false;
			synchronized (lock) {
				lock.notify();
			}
		}

		@Override
		public void run() {
			while (isRun) {
				try {
					if(isPause) {
						synchronized (lock) {
							lock.wait();
						}
					}
					
					if(gameRule != null) gameRule.detection(GameDirector.this);
					if(playScene != null) playScene.updateScene();
					
					try {Thread.sleep(60);} catch (InterruptedException e) {}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public interface CollisionDetection{
		public boolean detection(GameDirector gameDirector);
	}
	
	public interface PlayScene{
		public void addNode(Node node);
		public void updateScene();
		public int getWidth();
		public int getHeight();
	}
	
	public interface Node{
		public void draw(Graphics graphics);
	}
}
